<template>
  <div>
    <!-- 新建批次 -->
    <div class="returnConfirmNew" v-show="newBatch">
      <el-breadcrumb separator="/" style="font-size:16px;height:30px;">
        <el-breadcrumb-item :to="{ path: '/returnConfirm'}">回款确认</el-breadcrumb-item>
        <el-breadcrumb-item>新建批次</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="filter">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="城市：">
            <el-select v-model="cityId" placeholder="请选择城市" size="mini" filterable clearable @change="getCityId">
              <el-option :label="item.city" :value="item.cityId" v-for="(item,idx) in cityList" :key="idx"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="楼盘：">
            <el-select v-model="devId" placeholder="请选择楼盘" size="mini" filterable clearable>
              <el-option :label="item.devName" :value="item.devId" v-for="(item,idx) in devList" :key="idx"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户姓名：">
            <el-input v-model="customerName" placeholder="请输入客户姓名" size="mini"></el-input>
          </el-form-item>
          <el-form-item style="margin-top:-2px;margin-left:10px;">
            <el-button type="primary" @click="checkList" size="mini" id="monitorEnter">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="listData" border style="width: 100%" @selection-change="handleSelectionChangeNew">
        <el-table-column align="center" fixed type="selection" width="55"></el-table-column>
        <el-table-column align="center" fixed  label="序号" type="index" width="60"></el-table-column>
        <el-table-column align="center" prop="cityName" label="城市" width="150"></el-table-column>
        <el-table-column align="center" prop="customerName" label="客户姓名" width="150"></el-table-column>
        <el-table-column align="center" prop="customerPhone" label="手机号" width="150" :formatter="initPhone"></el-table-column>
        <el-table-column align="center" prop="houseNum" label="房源" width="200"></el-table-column>
        <el-table-column align="center" prop="devName" label="楼盘名称" width="300"></el-table-column>
        <el-table-column align="center" prop="amountTotalToBePay" label="应回款金额" width="120" :formatter="initMoney"></el-table-column>
        <el-table-column align="center" prop="afterAmountTotal" label="后佣回款" width="120" :formatter="initMoney"> </el-table-column>
        <el-table-column align="center" prop="awardAmountTotal" label="经纪人奖励" width="150" :formatter="initMoney"></el-table-column>
        <el-table-column align="center" prop="auditTime" label="佣金结算审核时间" width="180" :formatter="initTime"></el-table-column>
        <el-table-column align="center" prop="surplusAmount" label="待回款金额" width="180" :formatter="initMoney"></el-table-column>
        <el-table-column align="center" prop="amountRecieved" label="本次回款金额" width="180" :formatter="initMoney"></el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="pageData.pageNum"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageData.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="totalSize">
        </el-pagination>
      </div>
      <div style="text-align:center;margin-top:40px;margin-bottom:30px;">
        <el-button type="primary" @click="handleCancle" size="mini">返回</el-button>
        <el-button type="primary" @click="handleAddBatch(1)" size="mini">添加到批次</el-button>
        <el-button type="primary" @click="handleAddBatch(2)" size="mini">添加到批次到下一步</el-button>
      </div>
    </div>
    <!-- 下一步 -->
    <div class="returnConfirmNewNext" v-show="!newBatch">
      <el-table :data="listDataNext" ref="multipleTable" border style="width: 100%" @selection-change="handleSelectionChangeNewNext">
        <el-table-column align="center" fixed type="selection" width="55"></el-table-column>
        <el-table-column align="center" fixed  label="序号" type="index" width="60"></el-table-column>
        <el-table-column align="center" prop="cityName" label="城市" width="150"></el-table-column>
        <el-table-column align="center" prop="customerName" label="客户姓名" width="150"></el-table-column>
        <el-table-column align="center" prop="customerPhone" label="手机号" width="150" :formatter="initPhone"></el-table-column>
        <el-table-column align="center" prop="houseNum" label="房源" width="200"></el-table-column>
        <el-table-column align="center" prop="devName" label="楼盘名称" width="300"></el-table-column>
        <el-table-column align="center" prop="amountTotalToBePay" label="应回款金额" width="120" :formatter="initMoney"></el-table-column>
        <el-table-column align="center" prop="afterAmountTotal" label="后佣回款" width="120" :formatter="initMoney"> </el-table-column>
        <el-table-column align="center" prop="awardAmountTotal" label="经纪人奖励" width="150" :formatter="initMoney"></el-table-column>
        <el-table-column align="center" prop="auditTime" label="佣金结算审核时间" width="180" :formatter="initTime"></el-table-column>
        <el-table-column align="center" prop="surplusAmount" label="待回款金额" width="180" :formatter="initMoney"></el-table-column>
        <el-table-column align="center" prop="amountRecieved" label="本次回款金额" width="180" :formatter="initMoney"></el-table-column>
        <el-table-column align="center"  label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size='small' @click="adjustment(scope.row.index)">调整</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        title="调整回款金额"
        :visible.sync="dialogVisible"
        width="450px"
        :before-close="handleClose">
        <p>
          <span>应回款金额：</span>
          <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{dialogVisible? (listDataNext[index].amountTotalToBePay):'' | moneyFilter}}元</span>
        </p>
        <p>
          <span>待回款金额：</span>
          <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{dialogVisible? listDataNext[index].surplusAmount:'' | moneyFilter}}元</span>
        </p>
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="本次回款金额：">
            <el-input v-model="listDataNext[index].amountRecieved" placeholder="" @input="handleBlur" size="mini" v-if="dialogVisible" style="width:80%"></el-input>
            <span>元</span>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancle">取 消</el-button>
          <el-button type="primary" @click="confirm(listDataNext[index].amountRecieved)">确 定</el-button>
        </span>
      </el-dialog>
      <div class="part">
        <div class="txt">回款确认单：</div>
        <div class="content">
          <upload :multiple="true" ref="upload1" :fileList="renturnConfirmList"/>
        </div>
      </div>
      <div class="btn">
        <el-button type="primary" size="mini" @click="handleAdd">继续添加</el-button>
        <el-button type="primary" size="mini" @click="save(0)">保存</el-button>
        <el-button type="primary" size="mini" @click="save(1)">保存并提交审核</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import api from "@/api/apiPath"
import util from '@/common/utils'
import upload from '@/components/common/Upload'
export default {
  name:"returnConfirmNew",
  components: {
    upload
  },
  data() {
    return {
      newBatch:true,
      listData: [],
      listDataNext: [],
      renturnConfirmList:[],
      multipleSelection:[],
      multipleSelectionAll:[],
      multipleSelectionNext:[],
      cityList:[],
      cityId:'',
      devList:[],
      devId:'',
      idKey: "companyInfoId",
      tempcompanyInfoIdReturn:[],
      totalSize:0,
      pageData:{
        pageNum:1,
        pageSize:10
      },
      devInfo:{},
      renturnConfirmData:{
        pdfarr:[],
        pictures:[],
      },
      id:[],
      index:undefined,
      dialogVisible:false,
      tiaozhengListData:[],
      customerName:''
    }
  },
  mounted() {},
  filters:{
    moneyFilter(val){
      return util.formatMoney(val)
    }
  },
  created() {
    this.getCityList()
    this.getDevList()
    this.orderList(this.id)
    window.localStorage.removeItem('tempcompanyInfoIdReturn')
  },
  methods: {
    jiaoyan(val,confirm){
      if(!isNaN(val)){
        if(val>this.listDataNext[this.index].surplusAmount){
          this.$message({
            type:'warning',
            message:'本次回款金额不能大于待回款金额'
          })
          return
        }
        if(confirm == 1){
          this.dialogVisible = false
          let list = JSON.stringify(this.listDataNext)
          this.tiaozhengListData = JSON.parse(list)
        }
      }else{
        this.$message({
          type:'warning',
          message:'只能输入数字'
        })
        return
      }},
    // 校验调整本次回款金额
    handleBlur(val){
      this.jiaoyan(val)
    },
    // 点x关闭
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    // 取消
    cancle(){
      this.listDataNext[this.index].amountRecieved = this.tiaozhengListData[this.index].amountRecieved
      this.dialogVisible = false
    },
    confirm(val){
      this.jiaoyan(val,1)
    },
    // 调整
    adjustment(index){
      this.index = index
      this.dialogVisible = true
    },
    // 新建列表
    checkList(){
      if(window.localStorage.getItem("tempcompanyInfoIdReturn")){
        this.id = window.localStorage.getItem("tempcompanyInfoIdReturn").split(",")
      }
      this.pageData.pageNum = 1
      this.orderList(this.id)
    },
    // 返回佣金列表
    handleCancle(){
      this.$router.push('/returnConfirm')
    },
    // 添加到批次
    handleAddBatch(val){
      let listDataNextLength = this.listDataNext.length
      this.listDataNext = this.listDataNext.concat(this.multipleSelection)
      if (window.localStorage.getItem("tempcompanyInfoIdReturn")) {
        console.log(2);

        let tempcompanyInfoIdReturn = window.localStorage
          .getItem("tempcompanyInfoIdReturn")
          .split(",")
        window.localStorage.setItem(
          "tempcompanyInfoIdReturn",
          tempcompanyInfoIdReturn.concat(this.tempcompanyInfoIdReturn)
        )
      } else {
        console.log(1);
        console.log(this.tempcompanyInfoIdReturn);

        window.localStorage.setItem(
          "tempcompanyInfoIdReturn",
          this.tempcompanyInfoIdReturn
        )
      }
      if(val == 1){
        if(this.tempcompanyInfoIdReturn.length == 0){
          this.$message({
            type: "warning",
            message: "至少选择一条订单并添加到批次"
          })
          return
        }
        // 被选中的楼盘id
        let devId = []
        this.listDataNext.forEach(item=>{
          devId.push(item.devId)
        })
        if(Array.from(new Set(devId)).length!=1){
          this.$message.error('请选择同一楼盘的订单')
          this.listDataNext = this.listDataNext.splice(0,listDataNextLength)
          console.log(this.listDataNext)
          return
        }
        this.id = window.localStorage.getItem("tempcompanyInfoIdReturn").split(",")
        console.log(this.id);

        this.orderList(this.id)
        this.listDataNext.forEach((item,index)=>{
          item.index = index
        })
        let list = JSON.stringify(this.listDataNext)
        this.tiaozhengListData = JSON.parse(list)
        this.$message({
          type:'success',
          message:'成功添加'+this.tempcompanyInfoIdReturn.length+'条信息到批次'
        })
      }else if (val == 2){
        if(this.tempcompanyInfoIdReturn.length == 0 ){
          if(this.listDataNext.length == 0){
            this.$message({
              type: "warning",
              message: "至少选择一条订单并添加到批次"
            })
            return
          }
        }else{
          // 被选中的楼盘id
          let devId = []
          this.listDataNext.forEach(item=>{
            devId.push(item.devId)
          })
          if(Array.from(new Set(devId)).length!=1){
            this.$message.error('请选择同一楼盘的订单')
            this.listDataNext = this.listDataNext.splice(0,listDataNextLength)
            return
          }
          this.id = window.localStorage.getItem("tempcompanyInfoIdReturn").split(",");
          this.orderList(this.id)
          this.listDataNext.forEach((item,index)=>{
            item.index = index
          })
          let list = JSON.stringify(this.listDataNext)
          this.tiaozhengListData = JSON.parse(list)
          this.$message({
            type:'success',
            message:'成功添加'+this.tempcompanyInfoIdReturn.length+'条信息到批次'
          })
        }
        this.devInfo = this.listDataNext[0];
        this.newBatch = !this.newBatch;
      }
      this.toggleSelection(this.listDataNext)
    },
    toggleSelection(rows) {
      console.log(rows);
      if (rows) {
        this.$nextTick(()=>{
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row,true)
          })
        })
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 继续添加
    handleAdd(){
      this.newBatch = !this.newBatch
    },
    initPhone(row, column, cellValue, index){
      return util.formatPhoneNumber(cellValue)
    },
    initMoney(row, column, cellValue, index){
      return util.formatMoney(cellValue)
    },
    initTime(row, column, cellValue, index){
      return util.getTimeString(cellValue)
    },
    // 每页条数
    handleSizeChange(val) {
      this.pageData.pageSize = val;
      this.orderList(this.id)
    },
    // 下一页
    handleCurrentChange(val) {
      this.orderList(this.id)
    },
    // 订单总列表
    orderList(tempcompanyInfoId){
      let temId = [];
      if (tempcompanyInfoId == []) {
        temId = [];
      } else {
        temId = tempcompanyInfoId
      }

      this.axios.post(api.getBrokerageCompanyInfoReturnConfirmList,{
        pageNum:this.pageData.pageNum,
        pageSize:this.pageData.pageSize,
        devId:this.devId,
        cityId:this.cityId,
        tempcompanyInfoId:temId,
        customerName:this.customerName
      }).then(res=>{
        if(res.data.code == 200){
          this.totalSize = res.data.data.total
          this.listData = res.data.data.rows
          this.listData.forEach((item,index)=>{
            item.index = index
          })
        }
      })
    },
    // 新建批次-多选
    handleSelectionChangeNew(val) {
      this.multipleSelection = val
      setTimeout(()=>{
        this.changePageCoreRecordData()
      console.log(val);
      },300)
    },
    // 下一步多选
    handleSelectionChangeNewNext(val){
      this.multipleSelectionNext = val
    },
    // 城市列表
    getCityList(){
      this.axios.post(api.CITYLIST).then(res=>{
        if(res.data.code == 200){
          this.cityList = res.data.data.cityList
        }
      })
    },
    getCityId(val){
      this.getDevList(val)
      this.devId = ''
    },
    // 楼盘列表
    getDevList(val){
      this.axios.post(api.queryAllDevList,{
        cityId:val
      }).then(res=>{
        if(res.data.code == 200){
          this.devList = res.data.data
        }
      })
    },
    // 保存
    save(val){
      if(this.multipleSelectionNext.length == 0){
        this.$message({
          type:'warning',
          message:'请选择订单'
        })
        return
      }else{
        this.multipleSelectionNext.forEach((item,index)=>{
          item.dataIndex = index + 1
        })
      }
      Promise.all([
          this.$refs.upload1.submit()
        ]).then(res=>{
        if (res[0].length < 1) {
          this.$message({
              message: '回款确认单不能为空',
              type: 'warning'
          });
          return
        }
        // 回款确认单
        this.renturnConfirmData.pdfarr = []
        this.renturnConfirmData.pictures = []
        res[0].forEach(item=>{
          let suffix = item.substring(item.lastIndexOf('.')+1,item.length)
          if(suffix == 'pdf'){
            this.renturnConfirmData.pdfarr.push({
              name:item.substring(item.lastIndexOf('/')+1,item.length),
              url:item
            })
          }else{
            this.renturnConfirmData.pictures.push({
              name:item.substring(item.lastIndexOf('/')+1,item.length),
              url:item
            })
          }
        })
        this.axios.post(api.saveReturnConfirm,{
          auditStatus:val,
          data:this.multipleSelectionNext,
          pictureAddress:this.renturnConfirmData,// 回款确认单
        }).then(res=>{
          if(res.data.code == 200){
            this.$router.push({path:"/returnConfirm"})
          }
        })

      })
    },



    // 记忆选择核心方法
    changePageCoreRecordData() {
      // 标识当前行的唯一键的名称
      let idKey = this.idKey;
      let that = this;
      this.multipleSelectionAll = this.multipleSelection;
      // 总选择里面的key集合
      let selectAllIds = [];
      this.multipleSelectionAll.forEach(row => {
        selectAllIds.push(row[idKey]);
      });
      console.log('总选择的key', selectAllIds)
      this.tempcompanyInfoIdReturn = [];
      // 获取当前页选中的id
      this.multipleSelection.forEach(row => {
        this.tempcompanyInfoIdReturn.push(row[idKey]);
        // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
        if (selectAllIds.indexOf(row[idKey]) < 0) {
          that.multipleSelectionAll.push(row);
        }
      });
      console.log('当前也的选中id',this.tempcompanyInfoIdReturn)
      let noSelectIds = [];
      // 得到当前页没有选中的id
      this.listData.forEach(row => {
        if (this.tempcompanyInfoIdReturn.indexOf(row[idKey]) < 0) {
          noSelectIds.push(row[idKey]);
        }
      });
      noSelectIds.forEach(id => {
        if (selectAllIds.indexOf(id) >= 0) {
          for (let i = 0; i < that.multipleSelectionAll.length; i++) {
            if (that.multipleSelectionAll[i][idKey] == id) {
              // 如果总选择中有未被选中的，那么就删除这条
              that.multipleSelectionAll.splice(i, 1);
              break;
            }
          }
        }
      });
    },
  },
  computed: {}
}
</script>
<style lang="stylus" scoped>
  .returnConfirmNew {
    .block{
      margin-top :15px;
    }
  }
  .returnConfirmNewNext {
    .top{
      margin-bottom :15px;
      font-size :14px;
      color :#909399;
    }
    .one{
      margin-right :50px;
    }
    .pri{
      float :right;
      margin-bottom:15px;
    }
    .part{
      margin-top :30px;
      display:flex;
      font-size :14px;
      color :#909399;
    }
    .txt{
      width :200px;
    }
    .btn{
      margin-top :30px;
      padding-left :200px;
    }
    // .el-input{
    //   width:90%!important;
    // }
  }
</style>
